<script setup>
import {onMounted, ref} from 'vue';
import terminalComponent from './terminal.vue'
import tabsComponent from './tabs.vue'
import Bus from "@/utils/bus.js";
import apiAll from "@/api/apiAll.js";

const tabs = ref([{
  key: 'console',
  title: '终端控制台',
  delay: '9ms'
}])
const list = ref([])
const active = ref('console')
let index = 1;
const consoleInfo = ref([])
const loadingConsole = ref(false)

const handleAdd = () => {
  const key = 'key_' + new Date().getTime() + index
  const data = {
    key: key,
    title: '终端 - ' + index,
    content: 'terminal',
    delay: 0
  }
  list.value.push(data)
  active.value = key
  tabs.value.push(data)
  index++
};
const handleDelete = (key) => {
  // list.value = list.value.filter(e => e.key !== key)
  Bus.emit('shell', {type: 'delete', key})
};
const handleChange = (key) => {
  active.value = key
  if (key === 'console')
    getInfo()
}
const getInfo = () => {
  loadingConsole.value = true
  apiAll.commonApi.terminalConsole().then(res => {
    consoleInfo.value = [
      {label: '终端连接数', value: res.data.number},
      {label: '线程池接数', value: res.data.pool},
    ]
  }).finally(() => {
    setTimeout(() => {
      loadingConsole.value = false
    }, 300)
  })
}
const delayEvent = (key, delay) => {
  for (const e of tabs.value) {
    if (e.key === key) {
      e.delay = delay
      return
    }
  }
}

onMounted(() => {
  getInfo()
})

Bus.on('shell', data => {
  if (data.type === 'delete_terminal') {
    // console.log('delete_terminal: ' + JSON.stringify(data))
    list.value = list.value.filter(e => e.key !== data.key)
    tabs.value = tabs.value.filter(e => e.key !== data.key)
    active.value = tabs.value[tabs.value.length - 1].key
  }
})
</script>

<template>
  <div class="flex-column" style="width: 100%;height: 100%">
    <tabsComponent v-model="tabs" v-model:active="active"
                   @clickAdd="handleAdd" @clickRemove="handleDelete" @clickItem="handleChange"/>
    <div style="width: 100%;height: 100%;border: 1px solid blue">
      <div v-for="(item, index) of list">
        <terminalComponent :id="item.key" v-show="active===item.key" @delayEvent="delayEvent"/>
      </div>
      <a-spin :loading="loadingConsole" tip="刷新中...">
        <div v-show="active==='console'" class="flex-column" style="padding: 20px">
          <a-descriptions :data="consoleInfo" title="终端情况" :column="1"/>
          <h4>说明</h4>
          <span style="font-size: 14px">线程池线程空闲60秒后自动释放</span>
        </div>
      </a-spin>
    </div>
  </div>
</template>

<style scoped>

</style>